<?php
/**
 *  @author wyl
 *  @date 2015-8-17 15:13:35
 */
Yii::import('application.components.cronjob.class.*');
error_reporting(0);
class Cronjob extends CConsoleCommand{
	public $pid = 0;
	public $forever = false;
	public $sleep   = 0;
	public $commandPool;
	public $config;
	public $commandName;
	public $log;
	public $command;
	public $params;

	
	public $restart = false;
	
	public function init(){
		register_shutdown_function(array($this,'shutdown'));
		$this->pid = getmypid();
		
		$this->commandName = lcfirst(str_replace('Command',null,get_class($this)));
		
		$this->commandPool = new FilePool();
		$this->commandPool->setNamespace($this->commandName);
		$this->commandPool->setPrototype($this);
				
		$this->config = new FileConfig();
		$this->config->setNamespace($this->commandName);
			
		
		
		$this->log = new CronjobLog();
		$this->log->setNamespace($this->commandName);
		$this->log->addDir(date('Y'))->addDir(date('m'))->addDir(date('d'))->logFile($this->commandName);
		$this->log->addLog('START', 'Start the Command');
		$this->command='yiic '.$this->commandName;
	}
	
	public function shutdown(){
		$error=error_get_last();
		if($this->restart || !empty($error)){
			$this->log->addLog('ERROR', json_encode(error_get_last()));
			$start=new StartCommand();
			$start->run($this->commandName,array('forever',$this->sleep));
		}
	}
	
	public function command(){
		return array(
			'STOP' => 'endCronjob'
		);
	}
	
	public function endCronjob(){
		$this->log->addLog("END", 'End the Command');
		$this->afterRun();
		exit();
	}
	
	public function check(){
		exec('ps ax -o pid,cmd | grep yiic | grep -v grep | grep -v '.$this->pid,$return,$status);
		$cmds=array();
		foreach ($return as $ps){
			if(stripos($ps, $this->command)){
				return false;
			}else{
				continue;
			}
		} 
		return true;
	}
	
	public function beforeRun(){
		if(!$this->check()){
			$this->log->addLog('End', 'Start a existing command!');
			echo "You can't start a existing command!";
			$this->endCronjob();
		}
		return true;
	}
	
	public function afterRun(){
		$this->log->addLog("END", 'End the RUN');
		$this->commandPool->clear();
		$this->config->clear();
	}
	
	public function run($args){
		if (isset($args[0]) && $args[0] == 'forever') {
			$this->forever = true;
			$this->sleep = 1;
			if (isset($args[1]) && is_numeric($args[1])) {
				$this->sleep = $args[1];
			}
		}	
		$this->config->set(array(
			'forever' 	=> $this->forever,
			'sleep'		=> $this->sleep
		));
		if ($this->beforeRun()){
			do{
				try {
					$this->commandPool->runCommand();
					$this->log->addLog('INFO','run Base');
					$this->runBase();
				}catch (Exception $e){
					var_dump($e->getMessage());
					$this->log->addLog('ERROR',json_encode($e->getMessage()));
				}
				sleep($this->sleep);
			}while ($this->forever);
			$this->afterRun();
		}
	}
}
